package com.vim.common.aspect;

import com.vim.common.thread.SysLogThread;
import com.vim.common.thread.ThreadPool;
import com.vim.common.utils.RequestUtils;
import com.vim.modules.web.model.SysLog;
import com.vim.modules.web.model.SysUser;
import com.vim.modules.web.service.SysLogService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Aspect
@Component
public class LogAspect {

    @Value("${env_test}")
    private boolean envTest;

    @Resource
    private SysLogService sysLogService;

    @Pointcut("@annotation(com.vim.common.annotation.SysLogRecord)")
    public void sysLog(){}

    @Before("sysLog()")
    public void before(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        if(!envTest){
            SysLog sysLog = new SysLog();
            //类名
            sysLog.setClassName(joinPoint.getTarget().getClass().getName());
            //方法名称
            sysLog.setMethodName(joinPoint.getSignature().getName());
            //请求参数
            sysLog.setParams(RequestUtils.params(request));
            //操作人
            Subject subject = SecurityUtils.getSubject();
            if(subject != null && subject.isAuthenticated()){
                SysUser sysUser = (SysUser)subject.getPrincipal();
                sysLog.setUserId(sysUser.getUserId());
                sysLog.setUserName(sysUser.getNickname());
            }else{
                sysLog.setUserId("-1");
            }
            //时间
            sysLog.setCreateTime(new Date());

            //开启线程
            ThreadPool threadPool = ThreadPool.getInstance();
            SysLogThread thread = new SysLogThread(sysLogService, sysLog);
            threadPool.executorService.execute(thread);
        }
    }

    @AfterReturning(returning = "ret", pointcut = "sysLog()")
    public void afterReturning(Object ret) throws Throwable {
    }
}
